<template>
  <div class="search">
    <el-card>
        <el-row>
          <el-col :span="16">
            <el-form :model="searchForm" inline :label-width="100" class="search-form" style="width: 80%">
              <el-form-item label="所属分类">
                <el-select v-model="searchForm.categoryId"  style="width: 120px"  clearable>
                  <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"   placeholder="请选择分类名称"  style="width: 160px" />
                </el-select>
              </el-form-item>
              <el-form-item label="商品名" >
                <el-input type="text" v-model="searchForm.goodsName" clearable placeholder="请输入商品名" style="width: 160px" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit">搜索</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      <el-table :data="tableData" :row-key="row => row.id" style="width: 100%;" >
        <el-table-column prop="id" label="商品id" width="150"/>
        <el-table-column prop="name" label="商品名称" width="200"/>
        <el-table-column prop="spuPrice" label="商品价格" :formatter="formatPrice" width="200"/>
        <el-table-column prop="des" label="描述" width="300"/>
        <el-table-column prop="mainImage" label="主图信息" width="200">
          <!-- 图片的显示 -->
          <template #default="scope">
            <el-image :src="scope.row.mainImage" style="min-width: 35px;height: 35px"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="spuStatus" label="是否上架" width="150" >
                <template #default="scope">{{ scope.row.spuStatus === "0" ? '未上架' : '已上架' }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button link type="success" size="small" @click="getGoodsDetails(scope.row)">详情</el-button>
<!--            <el-button link type="primary" size="small" @click="toChangeGoods(scope.row)">编辑</el-button>-->
            <el-button link type="warning" size="small" @click="handleClick(scope.row)"
            >{{scope.row.spuStatus === '0' ?'上架':'下架'}}</el-button>
            <el-button link type="danger" size="small" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="total" @pagination="getPage" :limit="pageSize"></pagination>
    </el-card>
  </div>

  <!--商品详情展示-->
  <el-dialog v-model="showDialogDetail"  width="80%" title="商品详情" center>

    <el-form :label-width="120" :model="detailData" >
      <div class="base-info-item">
        <h4>基础信息</h4>
        <div class="form-item-view">
          <el-form-item label="商品分类">
              <span>{{
                  detailData.secCategoryVO.parentName
                }}</span>
            <span> &gt; {{ detailData.secCategoryVO.name }}</span>
          </el-form-item>
          <el-form-item label="商品名称">
              <span>{{
                  detailData.name
                }}</span>
          </el-form-item>
          <el-form-item label="spu价格">
              <span>{{
                  formatAPrice(detailData.spuPrice)
                }}</span>
          </el-form-item>
          <el-form-item label="商品描述">
              <span >{{
                  detailData.des
                }}</span>
          </el-form-item>
          <el-form-item label="商品品牌">
              <span class="goods-category-name">{{
                  detailData.brandVO.name
                }}</span>
          </el-form-item>
          <el-form-item label="详情介绍图">
             <span class="image-list">
                <img v-for="(image, index) in detailData.spuImageVOList" :src="image.image" :alt="'Image ' + (index + 1)" :key="index">
             </span>
          </el-form-item>
          <el-form-item label="基本属性信息">
            <!-- 属性 -->
            <ul class="attrs">
              <li v-for="item in detailData.spuAttrValueVOList" :key="item.value">
                <span class="dt">{{ item.keyName }}</span>
                <span class="dd">{{ item.value }}</span>
              </li>
            </ul>
          </el-form-item>
        </div>
      </div>
      <div class="base-info-item">
        <h4>sku信息</h4>
        <el-card>
        <div class="form-item-view">
            <el-table :data="detailData.goodsSkuVOList" style="width: 100%">
              <el-table-column prop="id" label="skuId" width="150" />
              <el-table-column prop="goodsName" label="商品名称" width="150" />
              <el-table-column prop="skuOldPrice" label="原价" width="150" />
              <el-table-column prop="skuPrice" label="现价" width="150" />
<!--              <el-table-column prop="skuStatus" label="是否上架" width="150" >
                <template #default="scope">{{ scope.row.skuStatus === "0" ? '未上架' : '已上架' }}</template>
              </el-table-column>-->
              <el-table-column prop="stock" label="库存" width="140" />
              <!--根据不同商品动态生成表头-->
              <el-table-column label="销售属性" width="150">
                <template #default="{ row }">
                  <ul>
                    <li v-for="attr in row.skuValueList" :key="attr.keyId">
                      {{ attr.keyName }}: {{ attr.value }}
                    </li>
                  </ul>
                </template>
              </el-table-column>
              <el-table-column label="商品图片">
                <template #default="{ row }">
                  <el-image
                      v-for="(item, index) in row.skuImageVOList"
                      :key="index"
                      :src="item.image"
                      style="width: 50px; height: 50px; margin-right: 5px;"
                  />
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="150">
                <template #default="scope">
<!--                    <el-button link type="danger" size="small" @click="handleClick(scope.row)"
                    >{{scope.row.skuStatus === "0" ?'上架':'下架'}}</el-button>-->
                  <el-button link type="success" size="small" @click="toChangeSkuGoodsStock(scope.row)">库存调整</el-button>
                </template>
              </el-table-column>
            </el-table>

        </div>
        </el-card>
      </div>
    </el-form>
  </el-dialog>

  <!--商品编辑-->
  <el-dialog v-model="showDialogChange" title="sku商品库存修改" width="32%" center>
      <el-form :model="changeForm" :rules="rules" ref="formRef" label-width="auto" style="max-width: 450px">
        <el-form-item label="sku商品库存" prop="stock">
          <el-input v-model="changeForm.stock" placeholder="请填写库存值"/>
        </el-form-item>
      </el-form>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="showDialogChange=false">取消</el-button>
      <el-button type="primary" @click="changeStock">确定</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import Pagination from "@/components/Pagination/index.vue";
import {changeStatusAPI, changeStockAPI, deleteGoodsAPI, getGoodsAPI, getGoodsDetailsAPI} from "@/api/GoodsManage.js";
import {getChildNameAPI} from "@/api/categoryManage.js";
import {ElMessage} from "element-plus";
// 格式化价格为两位小数
const formatPrice = (row, column, value) => {
  return parseFloat(value).toFixed(2)
};
const formatAPrice = (price) => {
  return parseFloat(price).toFixed(2);
};
const searchForm = reactive({
  goodsName:null,
  categoryId:null,
})

//基础商品数据
const tableData = ref([
  {
    id: '',
    name: '',
    spuPrice: '',
    des: '',
    mainImage: '',
    spuStatus:'',
  }
])
//详细商品数据
const detailData = ref(
  {
    id:'',
    des:'',
    name: "",
    spuPrice: '',
    secCategoryVO: {
      id: "",
      parentId: "",
      parentName: "",
      name: "",
      pic: '',
  },
    brandVO:{
      id: "",
      name: "",
      nameEn: "",
      logo: "",
      country: "",
      des: "",
      foundedTime: "",
      createTime: ""
    },
    spuImageVOList: [
      {
        id: "",
        spuId: "",
        image: "",
        des: '',
        sort: ""
      }],
    //商品spu对应spu属性list
    spuAttrValueVOList: [
      {
        keyName: "",
        value: ""
      }],
    goodsSkuVOList: [
      {
        id: "",
        spuId: "",
        goodsName: "",
        skuOldPrice: 0,
        skuPrice: 0,
        skuStatus: "",
        skuSort: 0,
        skuDiscount: "",
        sales: 0,
        stock: 0,
        skuValueList: [
          {
            keyId: "",
            keyName: "",
            value: '',
          }
        ],
        skuImageVOList: [
          {
            id: "",
            skuId: "",
            image: "",
            des: "",
            sort: 0
          }]
      }]
  }
)
const changeForm = ref({
  skuId:'',
  stock:'',
})
/*库存修改数据校验*/
const rules = {
  stock: [
    {required: true, message: '库存不能为空', trigger: 'blur'}
  ]
}
const formRef = ref({})
const current = ref(1)
const pageSize = ref(10)
const total = ref(100)
const categoryList = ref([{
  id:'',
  name:''
}])
const showDialogDetail = ref(false)
const showDialogChange = ref(false)
const getGoods = async () => {
  const res = await getGoodsAPI({current: current.value, pageSize: pageSize.value});
  tableData.value = res.data.records
  total.value = res.data.total
/*  skuValueHead.value = detailData.value.goodsSkuVOList[0].skuValueList
  console.log("skuValueHead",detailData.value.goodsSkuVOList[0].skuValueList)*/
}
onMounted(() => getGoods())
const getPage = (params) => {
  current.value = params.page
  pageSize.value = params.limit
    if(searchForm){
      onSubmit()
    }else {
      getGoods()
    }
}
//spu上下架
const handleClick = async (row) => {

  const params = ref({
    spuId:row.id,
    spuStatus:row.spuStatus
  })
  const res = await changeStatusAPI(params.value)
  if(res.data){
    await getGoods()
    ElMessage.success("修改成功")
  }
};
//条件搜索
const onSubmit = async ()=>{
  const categoryId = searchForm.categoryId
  const goodsName = searchForm.goodsName
  const params = ref({
    categoryId:categoryId,
    goodsName:goodsName,
    current:current.value,
    pageSize:pageSize.value
  })
  const res = await getGoodsAPI(params.value);
  tableData.value = res.data.records
  total.value = res.data.total
}

//获取商品详情
const getGoodsDetails = async (row) => {
  const res = await getGoodsDetailsAPI({id:row.id});
  detailData.value = res.data
  showDialogDetail.value = true
  console.log("res", detailData.value.secCategoryVO)
}

//修改sku库存
const changeStock = async () => {
  formRef.value.validate(async (valid) => {
    const res = await changeStockAPI(changeForm.value)
    if (res.data) {
      await getGoodsDetails
      ElMessage.success("库存修改成功")
      showDialogChange.value = false
    }
  })
};

//点击编辑显示
const toChangeSkuGoodsStock= async (row) => {
  //查询分类信息
  changeForm.value  = row
  changeForm.value.skuId  = row.id
  showDialogChange.value = true
}

//商品删除
const deleteRow = async (row) => {
  const res = await deleteGoodsAPI(row.id)
  if(res.data){
    await getGoods()
    ElMessage.success("删除成功");
  }
}

//初始化挂载
const getCategory = async ()=>{
  const res = await getChildNameAPI()
  categoryList.value = res.data
}
onMounted(() => getCategory())
</script>
<style>
div.base-info-item {
  h4 {
    margin-bottom: 10px;
    padding: 0 10px;
    border: 1px solid #ddd;
    background-color: #f8f8f8;
    font-weight: bold;
    color: #333;
    font-size: 14px;
    line-height: 40px;
    text-align: left;
  }

  >div {
    padding-left: 5%;
  }

  .form-item-view {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: space-between;

  }
  .image-list img {
    width: 100px; /* 设置图片宽度 */
    height: 100px; /* 设置图片高度 */
    margin-right: 10px; /* 设置图片之间的间距 */
  }
  .attrs {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 30px;

    li {
      display: flex;
      margin-bottom: 10px;
      width: 50%;

      .dt {
        width: 100px;
        color: #999;
      }

      .dd {
        flex: 1;
        color: #666;
      }
    }
  }
}
</style>